package com.soft.trading;

import android.view.accessibility.AccessibilityNodeInfo;

import com.soft.trading.service.AdvancedAccessibilityService;

import java.util.List;

/**
 * 工具类 - 提供查找节点的各种方法
 */
public class NodeFinder {

    /**
     * 通过资源ID查找节点
     */
    public static AccessibilityNodeInfo findNodeById(AccessibilityNodeInfo rootNode, String viewId) {
        if (rootNode == null || viewId == null) return null;

        List<AccessibilityNodeInfo> nodes = rootNode.findAccessibilityNodeInfosByViewId(viewId);
        return nodes.isEmpty() ? null : nodes.get(0);
    }

    /**
     * 通过文本内容查找节点
     */
    public static AccessibilityNodeInfo findNodeByText(AccessibilityNodeInfo rootNode, String text) {
        if (rootNode == null || text == null) return null;

        List<AccessibilityNodeInfo> nodes = rootNode.findAccessibilityNodeInfosByText(text);
        for (AccessibilityNodeInfo node : nodes) {
            if (node.isClickable() || node.isFocusable() || node.isEditable()) {
                return node;
            }
        }
        return nodes.isEmpty() ? null : nodes.get(0);
    }

    /**
     * 通过描述文本查找节点
     */
    public static AccessibilityNodeInfo findNodeByDescription(AccessibilityNodeInfo rootNode, String description) {
        if (rootNode == null || description == null) return null;

        return findNodeByDescriptionRecursive(rootNode, description);
    }

    private static AccessibilityNodeInfo findNodeByDescriptionRecursive(AccessibilityNodeInfo node, String description) {
        if (node == null) return null;

        if (node.getContentDescription() != null &&
                node.getContentDescription().toString().contains(description)) {
            return node;
        }

        for (int i = 0; i < node.getChildCount(); i++) {
            AccessibilityNodeInfo found = findNodeByDescriptionRecursive(node.getChild(i), description);
            if (found != null) return found;
        }

        return null;
    }

    /**
     * 获取根节点
     */
    public static AccessibilityNodeInfo getRootNode() {
        AdvancedAccessibilityService service = AdvancedAccessibilityService.getInstance();
        return service != null ? service.getRootInActiveWindow() : null;
    }

    /**
     * 执行点击操作
     */
    public static boolean performClick(AccessibilityNodeInfo node) {
        if (node == null) return false;

        if (node.isClickable()) {
            return node.performAction(AccessibilityNodeInfo.ACTION_CLICK);
        } else {
            // 如果节点不可点击，尝试点击其父节点
            AccessibilityNodeInfo parent = node.getParent();
            while (parent != null) {
                if (parent.isClickable()) {
                    return parent.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                }
                parent = parent.getParent();
            }
        }

        return false;
    }
}